from datetime import datetime
from flask import Blueprint, request, jsonify, make_response
from tanxi.models.user import User, db
from tanxi.admin.auth import generate_token, login_required

bp = Blueprint('client', __name__)

@bp.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    
    if not username or not password:
        return jsonify({'message': '用户名和密码不能为空', 'code': 400}), 400
        
    if User.query.filter_by(username=username).first():
        return jsonify({'message': '用户名已存在', 'code': 400}), 400
        
    if email and User.query.filter_by(email=email).first():
        return jsonify({'message': '邮箱已被使用', 'code': 400}), 400
        
    user = User(username=username, email=email)
    user.set_password(password)
    
    db.session.add(user)
    db.session.commit()
    
    return jsonify({'message': '注册成功', 'code': 200})

@bp.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return jsonify({'message': '用户名和密码不能为空', 'code': 400}), 400
        
    user = User.query.filter_by(username=username).first()
    if not user or not user.check_password(password):
        return jsonify({'message': '用户名或密码错误', 'code': 401}), 401
        
    # 更新最后登录时间
    user.last_login = datetime.utcnow()
    db.session.commit()
    
    # 生成token
    token = generate_token(user.id)
    
    # 设置响应
    response = make_response(jsonify({
        'message': '登录成功',
        'code': 200,
        'data': {
            'token': token,
            'user': user.to_dict()
        }
    }))
    
    # 设置cookie
    response.set_cookie(
        'token',
        token,
        httponly=True,
        secure=True,
        samesite='Lax',
        max_age=24*60*60  # 1天
    )
    
    return response

@bp.route('/api/user/info', methods=['GET'])
@login_required
def get_user_info():
    user = User.query.get(request.user_id)
    if not user:
        return jsonify({'message': '用户不存在', 'code': 404}), 404
    
    return jsonify({
        'code': 200,
        'data': user.to_dict()
    })

@bp.route('/api/logout', methods=['POST'])
@login_required
def logout():
    response = make_response(jsonify({
        'message': '退出登录成功',
        'code': 200
    }))
    
    # 清除cookie
    response.delete_cookie('token')
    
    return response